package com.stadium.handler;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.stadium.bean.User;
import com.stadium.servlet.UserServlet;
import com.stadium.tools.ResultMessage;

/*
 * 
 */
@Controller
public class UserHandler {

	private final Logger log = LoggerFactory.getLogger(UserHandler.class);

	@Autowired
	private UserServlet userServlet;

	// 登录
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public ResponseEntity<ResultMessage> login(
			@RequestParam(name = "account") String account,
			@RequestParam(name = "password") String password) {
		System.out.println("account:" + account);
		System.out.println("password:" + password);
		ResultMessage result = new ResultMessage();

		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(account,
				password);
		try {
			subject.login(token);
		} catch (ExcessiveAttemptsException eae) {
			result.getResultParm().put("code", "200");
			result.setResultInfo("账号被锁住，等待1分钟后再重试!");
			return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
		} catch (AuthenticationException ae) {
			result.getResultParm().put("code", "200");
			result.setResultInfo("账号或密码错误");
			return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
		}
		// 保存用户账号信息，便于后面与其他表关联
		Session session = subject.getSession();
		session.setAttribute("account", account);
		result.getResultParm().put("code", "100");
		result.setResultInfo("登录成功");
		result.getResultParm().put("user", session.getAttribute("user"));
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);

	}

	// 获取全部人员信息，除了超级管理员
	@RequiresRoles(value = { "admin" })
	@RequestMapping(value = "views/getAllUsers")
	public ResponseEntity<ResultMessage> getAllUsers() {

		List<User> users = userServlet.getAll();
		ResultMessage result = new ResultMessage();
		result.getResultParm().put("users", users);
		result.setResultInfo("查询成功!");
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}

	// 更新角色
	@RequiresRoles(value = { "admin" })
	@RequestMapping(value = "views/updateRole")
	public ResponseEntity<ResultMessage> updateRole(
			@RequestParam(name = "account") String account,
			@RequestParam(name = "role") Integer role) {
		log.info("更新角色");
		User user = userServlet.getByAccount(account);
		user.setRole(role);
		userServlet.save(user);

		ResultMessage result = new ResultMessage();
		result.setResultInfo("更新成功!");
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}
	
	//删除用户
	@RequiresRoles(value = { "admin" })
	@RequestMapping(value = "views/deleteUser")
	public ResponseEntity<ResultMessage> deleteUser(
			@RequestParam(name = "account") String account) {
		log.info("更新角色");
		User user = userServlet.getByAccount(account);
		user.setStatus(1);
		userServlet.save(user);

		ResultMessage result = new ResultMessage();
		result.setResultInfo("删除成功!");
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}

	// 添加用户并授权
	@RequiresRoles(value = { "admin" })
	@RequestMapping(value = "views/insertUser")
	public ResponseEntity<ResultMessage> insertUser(User user) {
		// 密码加密
		String account = user.getAccount();
		String passwordHash = encryPassword(account, account);

		user.setPassword(passwordHash);
		user.setStatus(0);
		userServlet.save(user);

		ResultMessage resultMessage = new ResultMessage();
		resultMessage.setResultInfo("添加成功");
		return new ResponseEntity<ResultMessage>(resultMessage, HttpStatus.OK);
	}

	// 普通用户注册
	@RequestMapping(value = "regist")
	public ResponseEntity<ResultMessage> regist(
			@RequestParam(name = "account") String account,
			@RequestParam(name = "password") String password,
			@RequestParam(name = "username") String username) {
		// 密码加密
		String passwordHash = encryPassword(account, password);

		User user = new User(null, username, account, passwordHash, 0, 0);
		userServlet.save(user);

		ResultMessage resultMessage = new ResultMessage();
		resultMessage.setResultInfo("注册成功！");
		return new ResponseEntity<ResultMessage>(resultMessage, HttpStatus.OK);
	}

	// 校验账号是否可用
	@RequestMapping(value = "checkAccount")
	public ResponseEntity<ResultMessage> checkAccount(
			@RequestParam(name = "account") String account) {
		ResultMessage result = new ResultMessage();

		User user = userServlet.getByAccount(account);
		if (user == null) {
			// code值为100，表示账号可用
			result.getResultParm().put("code", 100);
			result.setResultInfo("账号可用");
		} else {
			// code值为200，表示账号不可用
			result.getResultParm().put("code", 200);
			result.setResultInfo("账号不可用");
			result.getResultParm().put("user", user);
		}

		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}

	@RequiresRoles(value = { "admin" })
	@RequestMapping(value = "views/getUser")
	public ResponseEntity<ResultMessage> getUser(
			@RequestParam(name = "account") String account) {
		ResultMessage result = new ResultMessage();

		User user = userServlet.getByAccount(account);
		if (user == null) {
			// code值为100，表示账号可用
			result.getResultParm().put("code", 100);
			result.setResultInfo("账号可用");
		} else {
			// code值为200，表示账号不可用
			result.getResultParm().put("code", 200);
			result.setResultInfo("账号不可用");
			result.getResultParm().put("user", user);
		}
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}

	@RequestMapping(value = "views/changePassword")
	public ResponseEntity<ResultMessage> changePassword(
			@RequestParam("oldPassowrd") String oldPassword,
			@RequestParam("password") String password) {
		// 获取用户账号
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		String account = (String) session.getAttribute("account");
		// 获取账号对应的信息
		User user = userServlet.getByAccount(account);
		String oldPasswordEncry = encryPassword(account, oldPassword);
		ResultMessage result = new ResultMessage();
		if (!user.getPassword().equals(oldPasswordEncry)) {
			result.setResultInfo("旧密码错误，请重新输入");
			result.getResultParm().put("code", "200");
			return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
		} else {

			// 密码加密
			String passwordHash = encryPassword(account, password);
			user.setPassword(passwordHash);
			userServlet.save(user);
			result.setResultInfo("修改密码成功");
			result.getResultParm().put("code", "100");
			return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
		}
	}

	/*
	 * 密码加密方法 参数： account:账号 password:密码 返回加密密码
	 */
	protected String encryPassword(String account, String password) {
		ByteSource salt = ByteSource.Util.bytes(account);
		Object result = new SimpleHash("MD5", password, salt, 1024);
		return result.toString();
	}
}
